const data = [
  { id: 1, name: 'phone 1', price: 100 },
  { id: 2, name: 'phone 2', price: 100 },
  { id: 3, name: 'phone 3', price: 100 },
  { id: 4, name: 'phone 4', price: 100 },
  { id: 5, name: 'phone 5', price: 100 },
  { id: 6, name: 'phone 6', price: 100 },
  { id: 7, name: 'phone 7', price: 100 },
  { id: 8, name: 'phone 8', price: 100 },
  { id: 9, name: 'phone 9', price: 100 },
  { id: 10, name: 'phone 10', price: 100 },
  { id: 11, name: 'phone 11', price: 100 },
];

function getData(pageSize, pageIndex) {
  const start = pageSize * (pageIndex - 1);
  return data.slice(start, start + pageSize);
}

export default {
  'POST /mock/queryProduct': (req, res) => {
    const {
      body: { pageSize, pageIndex },
    } = req;
    return res.json({
      data: getData(pageSize, pageIndex),
      total: data.length,
    });
  },
  'POST /mock/addProduct': (req, res) => {
    const { body } = req;
    body.id = Math.random();
    data.push(body);
    res.json({
      success: true,
    });
  },
  'POST /mock/updateProduct': (req, res) => {
    const { body } = req;
    const { id, name, price } = body;
    const product = data.find(item => item.id === id);
    if (!product) {
      res.json({
        success: false,
      });
      return;
    }
    product.name = name;
    product.price = price;
    res.json({
      success: true,
    });
  },
  'GET /mock/deleteProduct': (req, res) => {
    const {
      query: { id },
    } = req;
    const index = data.findIndex(item => item.id.toString() === id);
    if (index < 0) {
      res.json({
        success: false,
      });
      return;
    }
    data.splice(index, 1);
    res.json({
      success: true,
    });
  },
};
